import java.io.UnsupportedEncodingException;

import com.xiaoleilu.hutool.util.StrUtil;

public class TLVDecoder {
	public static void main(String[] args) throws UnsupportedEncodingException {
		
		String body="00796002050000343030320005020131030438323336440312460145014F4608000331088880022F4704000000010806383838383838510862250000000000145E014F5F08000331088880022F6004000000013C1E494431383333313038313139393230343031313233344E4D3034D5C5C8FD 4347F06B4DA10232";
//		String body="005E6002050000343030320005000230300108BDBBD2D7B3C9B9A6020131030438323336440312460145014F4608000331088880022F4704000000010C083033313030303030510862250000000000142106383632333134 A0296C609CB5A75F";
//		String body="00024130010DB1A8CEC44D4143D0A3D1E9B4ED42011F43028236440820170815155149914508201708151551499146070003310888800247040000000151031234566103864313";
		Integer length = Integer.parseInt(StrUtil.sub(body, 0, 4),16)*2;
		//获取报文
		String body_tmp=StrUtil.sub(body, 4, 4+length+1);
		String TPDU= StrUtil.sub(body_tmp, 0, 10);
		String APPCODE= StrUtil.sub(body_tmp, 10, 20);
		String VERSION= StrUtil.sub(body_tmp, 20, 22);
		
		//域开始
		body_tmp=StrUtil.sub(body_tmp, 22, length);
		System.out.println(body_tmp);
		
//		decoder(body_tmp);
		decoder("42011F43028236440920170815161530501F450920170815161530501F4608000331088880022F47040000000108103946453945323535423631423031373351031234565F0312345660031234563C184D504E313131333930303030303030304E4D3034D5C5C8FD");
//		decoder("050134");
//		System.out.println(body_tmp);	
		
	}
	public static String[] decoder(String body) throws UnsupportedEncodingException {
		if(body.startsWith(" ")) {
			System.out.println("MAC:"+body);
			return null;
		}
		if(StrUtil.isEmpty(body)) {
			System.out.println("MAC:"+body);
			return null;
		}
		String[] bd=new String[3];

		String TAGIDs=StrUtil.sub(body, 0, 2);
		body=StrUtil.sub(body, 2, body.length());
		String TAGID=HEXUtil.hexString2binaryString(TAGIDs);
		//长度是否为2
		boolean extendBit=TAGID.charAt(0) == '1';
		//是否是BCD压缩
		boolean compressBit=TAGID.charAt(1) == '1';
		//域ID
		int tagBit=Integer.parseInt(StrUtil.sub(TAGID, 2, 8),2);
		
		String lengths=StrUtil.sub(body, 0, extendBit?4:2);
		int length=Integer.parseInt(lengths,16)*2;
		body=StrUtil.sub(body, extendBit?4:2, body.length());
		String value=StrUtil.sub(body, 0, length);
		body=StrUtil.sub(body, length, body.length());
		
		System.out.print(tagBit+"域\t"+length+"\t"+TAGID+"\tleng:"+extendBit+"\tisBCD:"+compressBit+"\t"+TAGIDs+lengths+value);
		if(compressBit) {
			if(value.endsWith("F")) {
				value=StrUtil.sub(value, 0, value.length()-1);
			}
		}else{
			
		}
		System.out.print("\t\t\t"+value);
		System.out.println();
		return decoder(body);
	}
}
